package leetcodev1.数组;

import java.util.List;

public class LeetCode120 {

    public int minimumTotal(List<List<Integer>> triangle) {
        int ret = Integer.MAX_VALUE;
        int rows = triangle.size();
        int columns = triangle.get(rows - 1).size();
        int[][] dict = new int[rows][columns];//可以优化成一个dict
        for (int i = 0; i < rows; i++) {
            int column = triangle.get(i).size();
            for (int j = 0; j < column; j++) {
                int num = triangle.get(i).get(j);
                if (i == 0) {
                    dict[0][j] = num;
                    continue;
                }

                if (j == 0) {
                    dict[i][j] = dict[i - 1][j] + num;
                    continue;
                }

                if (j == column - 1) {
                    dict[i][j] = dict[i - 1][j - 1] + num;
                    continue;
                }

                dict[i][j] = Math.min(triangle.get(i - 1).get(j - 1), triangle.get(i - 1).get(j)) + num;
            }
        }

        for (int i = 0; i < dict[0].length; i++) {
            ret = Math.min(ret, dict[rows - 1][i]);
        }

        return ret;
    }

    //干干净净
    public int minimumTotal1(List<List<Integer>> triangle) {
        int n = triangle.size();
        int[][] f = new int[n][n];
        f[0][0] = triangle.get(0).get(0);
        for (int i = 1; i < n; ++i) {
            f[i][0] = f[i - 1][0] + triangle.get(i).get(0);
            for (int j = 1; j < i; ++j) {
                f[i][j] = Math.min(f[i - 1][j - 1], f[i - 1][j]) + triangle.get(i).get(j);
            }
            f[i][i] = f[i - 1][i - 1] + triangle.get(i).get(i);
        }
        int minTotal = f[n - 1][0];
        for (int i = 1; i < n; ++i) {
            minTotal = Math.min(minTotal, f[n - 1][i]);
        }
        return minTotal;
    }

}
